import { ref, toRefs } from 'vue'
import { getDicts } from '@/api/sys/dict/data'
import store from '@/store'

const searchDictByKey = (dict, key) => {
    if (key === null && key === '') {
        return null
    }
    try {
        for (let i = 0; i < dict.length; i++) {
            if (dict[i].key === key) {
                return dict[i].value
            }
        }
    } catch (e) {
        return null
    }
}

/**
 * 获取字典数据
 */
export function getDict(...args) {
    const res = ref({})
    return (() => {
        args.forEach(dictType => {
            res.value[dictType] = []
            const storeDict = searchDictByKey(store.getters.dict, dictType)
            if (storeDict) {
                res.value[dictType] = storeDict.map(
                    p => ({ label: p.dictLabel, value: p.dictValue, elTagType: p.dictType })
                )
            } else {
                getDicts(dictType).then(result => {
                    store.dispatch('dict/setDict', { key: dictType, value: result.data })
                    res.value[dictType] = result.data.map(p => ({ label: p.dictLabel, value: p.dictValue, elTagType: p.dictType }));
                })
            }
        })
        return toRefs(res.value)
    })()
}